package cn.tedu.user.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
@ConfigurationProperties(prefix = "easymall.redis.cluster")
@Data
public class ClusterConfig {
    // 准备几个为bean对象创建做的属性
    List<String> nodes;
    Integer maxTotal;
    Integer maxIdle;
    Integer minIdle;

    @Bean
    public JedisCluster initJedisCluster() {
        // 收集节点信息, 解析nodes属性
        Set<HostAndPort> info = new HashSet<>();
        for (String node : nodes) {
            // node = "10.42.182.184:8000"
            String[] arr = node.split(":");
            String host = arr[0];
            int port = Integer.parseInt(arr[1]);
            info.add(new HostAndPort(host, port));
        }
        // 连接池的属性
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        return new JedisCluster(info, config);
    }
}
